/* model */
import { WebNotificationOptions } from '@service/WebNotificationService/model'
/* util */
import Log from '@src/util/log'

// 通知开启状态
const NotificationEnabledStatus = 'granted'
// 通知拒绝状态
const NotificationDeniedStatus = 'denied'

// 默认配置
const defaultOptions = {}

class WebNotificationService {
  
  options: WebNotificationOptions = defaultOptions
  notification: Notification | null = null
  
  constructor(options: WebNotificationOptions) {
    this.options = options || defaultOptions
  }
  
  /**
   * @description 是否支持浏览器通知功能
   * @return {boolean} 是否支持此功能
   */
  isSupported(): boolean {
    return window && 'Notification' in window;
  }
  
  isNotSupported(): boolean {
    return !this.isSupported()
  }
  
  /**
   * @description 请求通知权限
   * @return {Promise<boolean>} 是否授权通知
   */
  async requestPermission(): Promise<boolean> {
    
    // 检查通知权限是否开启
    if (Notification.permission === NotificationEnabledStatus) {
      return true
    }
    
    // 通知权限被禁用
    if (Notification.permission === NotificationDeniedStatus) {
      return false
    }
    
    // 询问开启通知权限
    return (
      Notification.requestPermission().then(function (permission) {
        
        // 如果用户同意授权
        if (permission === NotificationEnabledStatus) {
          return true
        }
        
        return false
      })
    )
    
  }
  
  async show(options: WebNotificationOptions = {}) {
    
    if (this.isNotSupported()) {
      return 
    }
    
    const isHavePermission = await this.requestPermission()
    if (!isHavePermission) {
      return 
    }
    
    const overrideOptions = Object.assign({}, this.options, options)
    
    this.notification = new Notification(overrideOptions.title || '', overrideOptions)
    
    this.notification.onclick = this.onClick.bind(this)
    this.notification.onerror = this.onError.bind(this)
    this.notification.onshow = this.onShow.bind(this)
    this.notification.onclose = this.onClose.bind(this)
    
  }
  
  onClick() {
    Log.info(null, this.onClick.name, this.onClick.name)
  }
  
  onError() {
    Log.info(null, this.onError.name, this.onError.name)
  }
  
  onShow() {
    Log.info(null, this.onShow.name, this.onShow.name)
  }
  
  onClose() {
    Log.info(null, this.onClose.name, this.onClose.name)
  }
  
}

export default WebNotificationService
